#include <QtGui>
#include "serialthread.h"

#if defined(Q_WS_WIN32)
#include <windows.h>
#endif

//#define SOCKET

SerialThread::SerialThread(SerialConsole *con, QObject *parent) : QThread(parent)
{
    connected = false;
    serialConsole = con;
#if defined(Q_WS_WIN32)
#endif
    //setTerminationEnabled(true);
#ifndef SOCKET
    //connect(this,SIGNAL(updateConsole(QByteArray*)),serialConsole,SLOT(update(QByteArray*)));
    connect(this,SIGNAL(updateConsole()),serialConsole,SLOT(update()));
#endif
}
SerialThread::~SerialThread()
{
    connected = false;
}

void SerialThread::startup(SerialPort *port)
{
    serialConsole->setPort(port);
    serialPort = port;
    connected = true;
#ifndef SOCKET
    this->start();
#endif
}

void SerialThread::stop()
{
    connected = false;
}

void SerialThread::run()
{
#ifndef SOCKET
    // run only if connected
    while(connected) {
#if 1
        if(this->serialPort->bytesAvailable() > 0)
            emit updateConsole();
#else
        if(this->serialPort->bytesAvailable() > 0)
            emit updateConsole(this->serialPort->readAll());
#endif
        // let application rest a little
        msleep(25);
    }
#endif
}

void SerialThread::socketUpdate(int handle)
{
    // according to Qt docs we need to do this sequence
    //
    socket->setEnabled(false);
    this->serialConsole->update(handle);
    socket->setEnabled(true);
}

void SerialThread::init(QString port, int baudrate)
{
    this->serialPort->init(port, baudrate);
}

bool SerialThread::open(void)
{
    serialConsole->setPort(serialPort);
    bool rc = this->serialPort->open();
    if(rc) {
        int handle = this->serialPort->getHandle();
#ifdef SOCKET
        socket = new QSocketNotifier(handle, QSocketNotifier::Read, this);
        connect(socket,SIGNAL(activated(int)),this,SLOT(socketUpdate(int)));
        if(socket->isEnabled() == false)
            socket->setEnabled(true);
#endif
    }
    return rc;
}

bool SerialThread::close(void)
{
    bool rc = this->serialPort->close();
#ifdef SOCKET
    if(socket != NULL) {
        disconnect(socket,SIGNAL(activated(int)),serialConsole,SLOT(update(int)));
        delete socket;
        socket = NULL;
    }
#endif
    return rc;
}
